package com.qianniu.napi.admin.web;

import akka.actor.ActorRef;
import akka.actor.Props;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.mapper.PintuanOpenMapper;
import com.qianniu.napi.admin.service.*;
import com.qianniu.napi.admin.service.akka.AkkaServer;
import com.qianniu.napi.admin.service.akka.ResourceActor;
import com.qianniu.napi.common.config.Constants;
import com.qianniu.napi.common.util.ObjectUtil;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 分类导航
 * </p>
 *
 * @author chenxuebin
 * @since 2018-10-17
 */
@Controller
public class NavController {

    private static final Logger logger = LoggerFactory.getLogger(NavController.class);

    @Autowired
    private INavService navService;
    @Autowired
    private IBannerService bannerService;
    @Autowired
    private INoticeService noticeService;
    @Autowired
    private IGoodsCategoryService gcService;
    @Autowired
    private IMerchantConfigService mcService;
    @Autowired
    private ICouponTplService couponTplService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private ICutpriceService cutpriceService;
    @Autowired
    private IPintuanService pintuanService;
    @Autowired
    private PintuanOpenMapper pintuanOpenMapper;
    @Autowired
    private IGoodsCategoryService goodscategoryService;
    @Autowired
    private IRedisService redisService;
    @Autowired
    private IStoreService storeService;
    @Autowired
    private IConfigService configService;

    @RequestMapping("admin/nav/index")
    public String index(Model model) {
        logger.debug(">>>>>>getIsAdmin=" + ObjectUtil.getIsAdmin());
        int isAdmin = ObjectUtil.getIsAdmin();
        if (isAdmin != 1) {
            List<Nav> list = navService.selectList(new EntityWrapper<Nav>().eq("is_system", 1));
            List<GoodsCategory> gclist = gcService.selectList(new EntityWrapper<GoodsCategory>().eq("mid", ObjectUtil.getMid()).eq("state", 1).isNotNull("pic"));
            model.addAttribute("list", list);
            model.addAttribute("gclist", gclist);

            List<Config> hylist = configService.selectList(new EntityWrapper<Config>().eq("mid", ObjectUtil.getMid()).eq("type", "hangyefenlei"));
            model.addAttribute("hylist", hylist);
        }
        model.addAttribute("isAdmin", ObjectUtil.getIsAdmin());
        return "admin/nav";
    }

    @RequestMapping("/admin/nav/list")
    @ResponseBody
    public Page<Nav> list(@RequestParam(value = "offset", required = false) Integer offset,
                          @RequestParam(value = "status", required = false) Integer status,
                          @RequestParam(value = "search", required = false) String search,
                          @RequestParam(value = "limit", required = false) Integer limit) {
        Wrapper<Nav> wrapper = new EntityWrapper<Nav>();
        int isAdmin = ObjectUtil.getIsAdmin();

//        if(isAdmin!=1)wrapper.eq("mid", ObjectUtil.getMid());
        // ******** 待完善 *******
        // ******** 实现更详细的权限结构后再更新 *******
        int utype = ObjectUtil.getUserType();
        if (ObjectUtil.getMpid() == null || ObjectUtil.getMpid() == 0)
            wrapper.eq("mid", ObjectUtil.getMid());
        else
            wrapper.eq("mpid", ObjectUtil.getMpid());

        if (!Strings.isNullOrEmpty(search)) wrapper.like("name", search);

        wrapper.orderBy("sort", true);
        Page<Nav> page = navService.selectPage(new Page<Nav>(offset / limit + 1, limit), wrapper);
        return page;
    }

    @RequestMapping("/admin/nav/add")
    public String add(Nav bean, BindingResult bindingResult, Model model) {
        logger.debug(">>>add bean 000=" + JSON.toJSONString(bean));
        // 字段校验
        bean.setCreatetime(new Date());
        bean.setMid(ObjectUtil.getMid());
        bean.setMpid(ObjectUtil.getMpid());
        bean.setUid(ObjectUtil.getUid());

        int isAdmin = ObjectUtil.getIsAdmin();
        if (isAdmin != 1) {
            List<Nav> list = navService.selectList(new EntityWrapper<Nav>().eq("is_system", 1));
            List<GoodsCategory> gclist = gcService.selectList(new EntityWrapper<GoodsCategory>().eq("mid", ObjectUtil.getMid()).eq("state", 1).isNotNull("pic"));
            model.addAttribute("list", list);
            model.addAttribute("gclist", gclist);

            List<Config> hylist = configService.selectList(new EntityWrapper<Config>().eq("mid", ObjectUtil.getMid()).eq("type", "hangyefenlei"));
            model.addAttribute("hylist", hylist);
        }
        model.addAttribute("isAdmin", ObjectUtil.getIsAdmin());

        if (bean.getNtype() == 2 && isAdmin != 1) {
            String nvalue = bean.getNvalue();
            if (!Strings.isNullOrEmpty(nvalue) && nvalue.contains("http")) {
                bean.setNvalue(nvalue.substring(0, nvalue.indexOf("http")));
                if (Strings.isNullOrEmpty(bean.getPic()))
                    bean.setPic(nvalue.substring(nvalue.indexOf("http")));
            }
        }

        Nav nav = navService.selectOne(new EntityWrapper<Nav>().eq("nvalue", bean.getNvalue()).eq("mpid", ObjectUtil.getMpid()));
        if (nav != null) {
            model.addAttribute("msg", "已存在分类导航");
            return "admin/nav";
        }
        if (bean.getNtype() == 2 && isAdmin == 1) {
            bean.setIsSystem(1);
        }
        if (bean.getSort() == null) {
            List<Nav> list = navService.selectList(new EntityWrapper<Nav>().eq("mid", ObjectUtil.getMid()));
            bean.setSort(list.size() + 1);
        }
        clearCache(ObjectUtil.getMpid());

        // ****** 待完善 ******
        // 系统后台登陆获取不到appid，先默认获取第一个MerchantConfig配置
//        MerchantConfig mc = mcService.selectOne(new EntityWrapper<MerchantConfig>().eq("mid", ObjectUtil.getMid()));
//        if (mc != null) {
//            mc.setVersion(1 + mc.getVersion());
//            mc.insertOrUpdate();
//        }

        logger.debug(">>>add bean after=" + JSON.toJSONString(bean));
        bean.insert();
        //更新资源文件
        AkkaServer.system.actorOf(Props.create(ResourceActor.class))
                .tell("Nav@" + bean.getId() + "@insert", ActorRef.noSender());

        return "admin/nav";
    }

    @RequestMapping("/admin/nav/getNavById")
    @ResponseBody
    public Nav getNavById(long id) {
        Nav nav = navService.selectById(id);
        return nav;
    }

    @RequestMapping("/admin/nav/deleteOne")
    @ResponseBody
    public int deleteOne(long id) {

        Nav nav = navService.selectById(id);
        Long cid = nav.getCid();
        if (cid != null) {
            GoodsCategory gc = gcService.selectById(cid);
            if (gc != null) {
                gc.setIsNav(-1);
                gc.updateById();
            }
        }
        clearCache(nav.getMpid());
        boolean isSucc = navService.deleteById(id);
        return isSucc ? 1 : 0;
    }

    @RequestMapping("/admin/nav/changeState")
    @ResponseBody
    public String changeState(long id, int state) {
        Nav bean = new Nav();
        bean.setId(id);
        bean.setState(state);
        bean.setModifytime(new Date());
        bean.setModifier(ObjectUtil.getUid());
        navService.updateById(bean);
        Nav nav = navService.selectById(bean.getId());
        clearCache(nav.getMpid());
        return "success";
    }

    @RequestMapping("/admin/nav/modify")
    public String update(Nav bean) {
        bean.setModifytime(new Date());
        bean.setModifier(ObjectUtil.getUid());
        boolean isSuccc = navService.updateById(bean);
        Nav nav = navService.selectById(bean.getId());
        clearCache(nav.getMpid());
        if (isSuccc) {
            //更新资源文件
            AkkaServer.system.actorOf(Props.create(ResourceActor.class))
                    .tell("Nav@" + bean.getId() + "@update", ActorRef.noSender());
            return "redirect:index";
        }
        return "error";
    }

    @RequestMapping("/admin/nav/moveSore")
    @ResponseBody
    public Boolean moveSore(long currendId, int currentSort, long moveId, int moveSort) {
        logger.info("moveSore");
        logger.info("currendId:" + currendId);
        logger.info("currentSort:" + currentSort);
        logger.info("moveId:" + moveId);
        logger.info("moveSort:" + moveSort);
        List<Nav> navList = new ArrayList<Nav>();

        Nav moveNav = new Nav();
        moveNav.setId(moveId);
        moveNav.setSort(currentSort);
        moveNav.setModifytime(new Date());
        moveNav.setModifier(ObjectUtil.getUid());
        //navService.updateById(moveNav);
        navList.add(moveNav);

        Nav currentNav = new Nav();
        currentNav.setId(currendId);
        currentNav.setSort(moveSort);
        currentNav.setModifytime(new Date());
        currentNav.setModifier(ObjectUtil.getUid());
        //navService.updateById(currentNav);
        navList.add(currentNav);

        Nav nav = navService.selectById(moveId);
        clearCache(nav.getMpid());

        return navService.updateBatchById(navList);
    }

    @RequestMapping("/admin/nav/checknav")
    @ResponseBody
    public Jinfo checknav(String nvalue, Integer ntype) {
        Jinfo jinfo = new Jinfo();

        Wrapper<Nav> wrapper = new EntityWrapper<Nav>();
        wrapper.where("nvalue={0} and ntype={1}", nvalue, ntype)
                .eq("mpid", ObjectUtil.getMpid());
        List<Nav> existList = navService.selectList(wrapper);
        if (existList != null && existList.size() > 0) {
            jinfo.setCode(1);
            jinfo.setMsg("已存在该分类导航");
            return jinfo;
        }

        return jinfo;
    }

    private void clearCache(Long mpid) {
        String rkey = Constants.REDIS_APP_INIT + mpid;
        redisService.del(rkey);
    }

}
